
import SwiftUI
import GRDB

struct DuetContactView: View {
    let row: Row

    var body: some View {
        List {
            Group {
                row.cell(name: "Name", key: "ZDISPLAYNAME")
                row.cell(name: "ID", key: "ZIDENTIFIER")
                row.cell(name: "Custom ID", key: "ZCUSTOMIDENTIFIER")
                row.numberCell(name: "Incoming Recipient Count", key: "ZINCOMINGRECIPIENTCOUNT")
                row.numberCell(name: "Incoming Sender Count", key: "ZINCOMINGSENDERCOUNT")
                row.numberCell(name: "Outgoing Recipient Count", key: "ZOUTGOINGRECIPIENTCOUNT")
                row.dateCell(name: "Creation Date", key: "ZCREATIONDATE")
                row.dateCell(name: "First Incoming Recipient Date", key: "ZFIRSTINCOMINGRECIPIENTDATE")
            }
            row.dateCell(name: "First Incoming Sender Date", key: "ZFIRSTINCOMINGSENDERDATE")
            row.dateCell(name: "First Outgoing Recipient Date", key: "ZFIRSTOUTGOINGRECIPIENTDATE")
            row.dateCell(name: "Last Incoming Recipient Date", key: "ZLASTINCOMINGRECIPIENTDATE")
            row.dateCell(name: "Last Incoming Sender Date", key: "ZLASTINCOMINGSENDERDATE")
            row.dateCell(name: "Last Outgoing Recipient Date", key: "ZLASTOUTGOINGRECIPIENTDATE")
            row.dateCell(name: "Last Outgoing Recipient Date", key: "ZLASTOUTGOINGRECIPIENTDATE")
            row.cell(name: "Person ID", key: "ZPERSONID")
        }
    }

}

extension Row {
    func cell(name: String, key: String) -> some View {
        if let value: String = self[key] {
            return AnyView(HStack {
                Text(name)
                Spacer()
                Text(value)
            })
        } else {
            return AnyView(EmptyView())
        }
    }

    func numberCell(name: String, key: String) -> some View {
        if let value: Int = self[key] {
            return AnyView(HStack {
                Text(name)
                Spacer()
                Text("\(value)")
            })
        } else {
            return AnyView(EmptyView())
        }
    }

    func dateCell(name: String, key: String) -> some View {
        if let value: Double = self[key] {
            return AnyView(HStack {
                Text(name)
                Spacer()
                Text(DateFormatter.formatter.string(from: Date(timeIntervalSinceReferenceDate: value)))
            })
        } else {
            return AnyView(EmptyView())
        }
    }
}

extension DateFormatter {
    static let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = .autoupdatingCurrent
        formatter.timeZone = .autoupdatingCurrent
        formatter.dateStyle = .medium
        formatter.timeStyle = .short
        return formatter
    }()
}

//struct DuetContactView_Previews: PreviewProvider {
//    static var previews: some View {
//        DuetContactView()
//    }
//}
